$(function () {
    var $env = $('#env');
    if($env.length>0) {
        $env.val($.cookie('env'));
        if ($.trim($env.val()) === '') {
            $("#env option:first").prop("selected", 'selected');
            $.cookie('env', $env.val(), {path: '/'});
        }
        $env.change(function () {
            $.cookie('env', $env.val(), {path: '/'});
            window.location.reload(true);
        });
    }
});

function newUser() {
    var saveFunction;

    top.layer.open({
        type: 2,
        title: 'New User',
        area: ["310px","490px"],
        zIndex: top.layer.zIndex,
        anim: 0,
        shadeClose: true,
        resize: true,
        btn: ['保存', '取消'],
        content: '/users/add_new.htm',
        success: function (layero, index) {
            var body = top.layer.getChildFrame('body', index);
            var iframeWin = window[layero.find('iframe')[0]['name']];
            saveFunction = iframeWin.save;
        },
        yes: function () {
            saveFunction(function () {});
        },
        btn2: function () {
            layer.closeAll();
        }

    });
}

//发布项目
function publishProject(project) {
    publish('publish Project:' + env + "." + project, '/release/project.json', {project: project});
}

//发布环境
function publishEnv(env) {
    publish('publish Environment:' + env, '/release/env.json', {env: env});
}

function publish(msg, url, data) {
    top.layer.prompt(
        {
            formType: 2,
            title: msg,
            value: "release message",
            shadeClose: true,
            anim: 0
        },
        function (val, index) {

            if (!val || $.trim(val).length <= 0 || $.trim(val) === 'release message') {
                top.layer.msg("please input release message!");
                return;
            }

            var loadingLayerHandler;
            $.ajax({
                url: url,
                type: 'post',
                data: $.extend(data, {msg: val}),
                beforeSend: function () {
                    loadingLayerHandler = top.layer.msg('正在操作...', {
                        icon: 16,
                        shade: 0.5,
                        scrollbar: false,
                        zIndex: top.layer.zIndex,
                        anim: 0
                    });
                },
                success: function (data) {
                    top.layer.close(loadingLayerHandler);
                    if (!data.success) {
                        top.layer.open({
                            title: '错误',
                            content: data.msg,
                            shadeClose: true,
                            icon: 2,
                            anim: 0,
                            zIndex: top.layer.zIndex
                        });
                        return;
                    }
                    top.layer.open({
                        title: '成功',
                        content: data.msg,
                        shadeClose: true,
                        icon: 1,
                        anim: 0,
                        zIndex: top.layer.zIndex
                    });
                    top.layer.closeAll();
                },
                error: function (e) {
                    top.layer.close(loadingLayerHandler);
                    top.layer.open({
                        title: '发生错误',
                        content: JSON.stringify(e),
                        shadeClose: true,
                        icon: 2,
                        zIndex: top.layer.zIndex,
                        anim: 0
                    });
                }
            });
        });
}

// 关闭当前窗口
function closeWindow() {
    if (top != null) {
        var index = top.layer.getFrameIndex(window.name);
        top.layer.close(index);
    }
}

// 表单序列化成json
function getFormJson(form) {
    var o = {};
    var a = $(form).serializeArray();
    $.each(a, function () {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
}

function numdate(javaTimestamp) {
    var timestamp = moment(new Date(parseInt(javaTimestamp)));
    return timestamp.format("YYYY-MM-DD HH:mm:ss")
}

function deleteFile(path) {

    top.layer.confirm('真的删除文件(文件夹)\'' + path + '\'?',
        {btn: ['确定', '取消'], shadeClose: true, anim: 0},
        function (index) {
            $.ajax({
                url: '/config_file_delete.json',
                type: 'post',
                data: {path: path},
                success: function (data) {
                    if (!data.success) {
                        top.layer.open({
                            title: '错误',
                            content: data.msg,
                            shadeClose: true,
                            anim: 0,
                            zIndex: top.layer.zIndex
                        });
                        return;
                    }
                    top.location.reload(true);
                },
                error: function (e) {
                    // 关闭遮罩层
                    top.layer.open({
                        title: '发生错误',
                        content: JSON.stringify(e),
                        shadeClose: true,
                        zIndex: top.layer.zIndex,
                        anim: 0
                    });
                }
            });


        });
}

function deleteProject(project) {

    top.layer.confirm('真的删除\'' + project + '\'项目?',
        {btn: ['确定', '取消'], shadeClose: true, anim: 0},
        function (index) {
            $.ajax({
                url: '/project/'+project,
                type: 'delete',
                success: function (data) {
                    if (!data.success) {
                        top.layer.open({
                            title: '错误',
                            content: data.msg,
                            shadeClose: true,
                            anim: 0,
                            zIndex: top.layer.zIndex
                        });
                        return;
                    }
                    top.location.reload(true);
                },
                error: function (e) {
                    // 关闭遮罩层
                    top.layer.open({
                        title: '发生错误',
                        content: JSON.stringify(e),
                        shadeClose: true,
                        zIndex: top.layer.zIndex,
                        anim: 0
                    });
                }
            });


        });
}

function newConfigFile() {

    top.layer.prompt(
        {
            title: 'filePath, ex: path/to/file.yml',
            value: 'path/to/file.yml',
            shadeClose: true,
            anim: 0
        },
        function (val, index) {
            $.ajax({
                url: '/config_file_edit/verify_name',
                type: 'get',
                data: {path: val},
                success: function (data) {
                    if (!data.success) {
                        top.layer.open({
                            title: '错误',
                            content: data.msg,
                            shadeClose: true,
                            anim: 0,
                            zIndex: top.layer.zIndex,
                        });
                        return;
                    }
                    top.location.href = '/config_file_edit/' + data.href;
                },
                error: function (e) {
                    // 关闭遮罩层
                    top.layer.open({
                        title: '发生错误',
                        content: JSON.stringify(e),
                        shadeClose: true,
                        zIndex: top.layer.zIndex,
                        anim: 0
                    });
                }
            });


        });
}

function newProject(callBack) {
    var saveFunction;

    top.layer.prompt(
        {
            title: 'project name',
            value: '',
            shadeClose: true,
            anim: 0
        },
        function (val, index) {
            $.ajax({
                url: '/projects/verify_name',
                type: 'get',
                data: {project: val},
                success: function (data) {
                    if (!data.success) {
                        top.layer.open({
                            title: '错误',
                            content: data.msg,
                            shadeClose: true,
                            anim: 0,
                            zIndex: top.layer.zIndex,
                        });
                        return;
                    }

                    top.layer.closeAll();
                    top.layer.open({
                        type: 2,
                        title: 'newProject: ' + val,
                        shadeClose: true,
                        resize: true,
                        anim: 0,
                        skin: 'layer-class',
                        area: ['550px', '400px'],
                        content: '/project/'+val+'/struct',
                        btn: ['保存', '取消'],
                        yes: function () {
                            saveFunction(function () {
                                top.location.reload(true)
                            });
                        },
                        btn2: function () {
                            layer.closeAll();
                        },
                        zIndex: top.layer.zIndex,
                        success: function (layero, index) {
                            var body = top.layer.getChildFrame('body', index);
                            var iframeWin = window[layero.find('iframe')[0]['name']];
                            saveFunction = iframeWin.save;
                        }
                    });
                },
                error: function (e) {
                    // 关闭遮罩层
                    top.layer.open({
                        title: '发生错误',
                        content: JSON.stringify(e),
                        shadeClose: true,
                        zIndex: top.layer.zIndex,
                        anim: 0
                    });
                }
            });


        });


}

function editProject(project) {
    var saveFunction;
    layer.open({
        type: 2, title: 'project: ' + project, shadeClose: true, resize: true, anim: 0, skin: 'layer-class'
        , area: ['550px', '400px']
        , content: '/project/' + project + '/struct'
        , btn: ['保存', '取消']
        , yes: function () {
            saveFunction();
        }
        , btn2: function () {
            layer.closeAll();
        }
        , zIndex: layer.zIndex
        , success: function (layero, index) {
            var body = top.layer.getChildFrame('body', index);
            var iframeWin = window[layero.find('iframe')[0]['name']];
            saveFunction = iframeWin.save;
        }
    });
}

function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=")
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1
            c_end = document.cookie.indexOf(";", c_start)
            if (c_end == -1) c_end = document.cookie.length
            return unescape(document.cookie.substring(c_start, c_end))
        }
    }
    return ""
}

function setCookie(c_name, value, expiredays) {
    var exdate = new Date()
    exdate.setDate(exdate.getDate() + expiredays)
    document.cookie = c_name + "=" + escape(value) +
        ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString()) +
        ";path=/";
}